package com.ita.os.client.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.ita.os.client.dao.DishDao;
import com.ita.os.client.po.Dish;
import com.ita.os.client.po.Page;
import com.ita.os.client.util.DbUtil;

public class DishDaoImpl implements DishDao{

	@Override
	public List<Dish> listDishes(Page p,int mid) {
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		List<Dish> listDish = null;
		try {
			con = DbUtil.connect();
			listDish = new ArrayList<Dish>();
			String sql = "select * from (select ROWNUM rn, d.* from (select * from dish where mid = ?) d where ROWNUM <=?) where rn >=?";
			pst = con.prepareStatement(sql);
			pst.setInt(1,mid);
			pst.setInt(2, p.getCurPage()*p.getPageSize());
			pst.setInt(3, p.getStartPage());
			rs= pst.executeQuery();
			Dish d = null;
			while (rs.next()) {
				d = new Dish();
				d.setDid(rs.getInt("did"));
				d.setDname(rs.getString("dname"));
				d.setImg(rs.getString("img"));
				d.setPrice(rs.getInt("price"));
				d.setMid(mid);
				listDish.add(d);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
		DbUtil.free(con, pst, rs);
		}
		return listDish;
	}

	@Override
	public int countDishes(int mid) {
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		int count = 0;
		try {
			con = DbUtil.connect();
			String sql = "select count(*) as count from dish where mid=?";
			pst = con.prepareStatement(sql);
			pst.setInt(1, mid);
			rs= pst.executeQuery();
			rs.next();
			count = rs.getInt("count");
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DbUtil.free(con, pst, rs);
		}
		return count;
	}

}
